package com.example.crm.controller;

import com.example.crm.entity.SalesProcess;
import com.example.crm.entity.SalesStage;
import com.example.crm.service.SalesProcessService;
import com.example.crm.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 销售流程控制器
 */
@RestController
@RequestMapping("/api/sales/process")
public class SalesProcessController {

    @Autowired
    private SalesProcessService salesProcessService;

    /**
     * 获取流程列表
     */
    @GetMapping("/list")
    public Result<List<SalesProcess>> list() {
        return Result.success(salesProcessService.listProcesses());
    }

    /**
     * 获取流程详情
     */
    @GetMapping("/{id}")
    public Result<SalesProcess> getById(@PathVariable Long id) {
        return Result.success(salesProcessService.getProcessDetail(id));
    }

    /**
     * 添加流程
     */
    @PostMapping
    public Result<Boolean> save(@RequestBody Map<String, Object> params) {
        SalesProcess process = new SalesProcess();
        process.setName((String) params.get("name"));
        process.setDescription((String) params.get("description"));
        
        // 处理isDefault可能为null的情况
        Boolean isDefault = (Boolean) params.get("isDefault");
        process.setIsDefault(isDefault != null ? isDefault : false);
        
        // 设置创建人ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        process.setCreatorId(1L); // 此处应查询用户ID，这里简化处理
        
        // 获取阶段列表
        List<Map<String, Object>> stageList = (List<Map<String, Object>>) params.get("stages");
        List<SalesStage> stages = createStagesFromMap(stageList);
        
        boolean success = salesProcessService.addProcess(process, stages);
        
        return Result.success(success);
    }

    /**
     * 更新流程
     */
    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        SalesProcess process = new SalesProcess();
        process.setId(id);
        process.setName((String) params.get("name"));
        process.setDescription((String) params.get("description"));
        
        // 处理isDefault可能为null的情况
        Boolean isDefault = (Boolean) params.get("isDefault");
        process.setIsDefault(isDefault != null ? isDefault : false);
        
        // 获取阶段列表
        List<Map<String, Object>> stageList = (List<Map<String, Object>>) params.get("stages");
        List<SalesStage> stages = createStagesFromMap(stageList);
        
        boolean success = salesProcessService.updateProcess(process, stages);
        
        return Result.success(success);
    }

    /**
     * 删除流程
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(salesProcessService.removeById(id));
    }

    /**
     * 设置默认流程
     */
    @PostMapping("/default/{id}")
    public Result<Boolean> setDefault(@PathVariable Long id) {
        return Result.success(salesProcessService.setDefaultProcess(id));
    }

    /**
     * 获取默认流程
     */
    @GetMapping("/default")
    public Result<SalesProcess> getDefault() {
        return Result.success(salesProcessService.getDefaultProcess());
    }
    
    /**
     * 从Map创建阶段对象列表
     */
    private List<SalesStage> createStagesFromMap(List<Map<String, Object>> stageList) {
        if (stageList == null || stageList.isEmpty()) {
            return new ArrayList<>();
        }
        
        return stageList.stream().map(map -> {
            SalesStage stage = new SalesStage();
            if (map.containsKey("id")) {
                stage.setId(Long.valueOf(map.get("id").toString()));
            }
            stage.setName((String) map.get("name"));
            
            // 安全处理可能为null的字段
            if (map.containsKey("description")) {
                stage.setDescription((String) map.get("description"));
            }
            
            if (map.containsKey("winRate")) {
                stage.setWinRate(Integer.valueOf(map.get("winRate").toString()));
            } else {
                stage.setWinRate(50); // 默认值
            }
            
            if (map.containsKey("orderNum")) {
                stage.setOrderNum(Integer.valueOf(map.get("orderNum").toString()));
            } else {
                stage.setOrderNum(1); // 默认值
            }
            
            if (map.containsKey("requiredFields")) {
                stage.setRequiredFields((String) map.get("requiredFields"));
            }
            
            if (map.containsKey("expectedDays")) {
                stage.setExpectedDays(Integer.valueOf(map.get("expectedDays").toString()));
            }
            
            return stage;
        }).collect(Collectors.toList());
    }
} 